package com.xiaohudie.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @Author xiao hu die
 * @Date 2022/3/6 14:25
 * @Version 1.0
 */
/**生成全局唯怡ID
 * 时间戳加序列号*/
@Component
public class RedisIdWork {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private static final int COUNT_BITS=32;
    public static long ShiJianChu(){
        LocalDateTime time = LocalDateTime.of(2022, 1, 1, 0, 0);
        long second = time.toEpochSecond(ZoneOffset.MAX);
        return second;
    }
    private  static  final long BEGIN_TIMESTAMP=RedisIdWork.ShiJianChu();
    public long nextId(String keyPrefix){
        /**生成时间戳*/
        /**生成当前时间戳*/
        LocalDateTime now = LocalDateTime.now();
        long second = now.toEpochSecond(ZoneOffset.MAX);
        long shijianchuo   =   second- BEGIN_TIMESTAMP;
        /**生成序列化*/
        /**获取日期精确到天*/
        String yyyyMMdd = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        /**自增长*/
        Long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + yyyyMMdd);
        /**进行序列化拼接*/
        long xuleihao = shijianchuo<<COUNT_BITS | increment;
        return xuleihao;
    }
}
